package com.lingdian.resume.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.SortField.Type;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.lionsoul.jcseg.analyzer.JcsegAnalyzer;
import org.lionsoul.jcseg.tokenizer.core.JcsegTaskConfig;
import org.springframework.stereotype.Service;

import com.lingdian.resume.bean.ResumeInfo;
import com.lingdian.resume.service.LuceneResumeInfoService;
@Service("luceneResumeInfoService")
public class LuceneResumeInfoServiceImpl implements LuceneResumeInfoService {
	private final String indexPath =getClass().getClassLoader().getResource("").getPath();
	@Override
	public void createIndex(Iterator<ResumeInfo> resumeInfos) {

		// 索引位置
		Path path = new File(indexPath).toPath();
		// 创建标准分词器(对中文的匹配不好)
		Analyzer analyzer = new StandardAnalyzer();
//		Analyzer analyzer = new JcsegAnalyzer(JcsegTaskConfig.COMPLEX_MODE);
		Directory directory;// 声明文件目录
		
		IndexWriterConfig config = new IndexWriterConfig(analyzer);// 将分词器配置到索引配置里
		IndexWriter iwriter;// 声明索引
		try {
			directory = FSDirectory.open(path);// 创建文件目录

			iwriter = new IndexWriter(directory, config);// 初始化索引
			while(resumeInfos.hasNext()){
				ResumeInfo info = resumeInfos.next();
				String text = info.getText();
				Document doc = new Document();
				doc.add(new Field("htmlText", text, TextField.TYPE_STORED));
				iwriter.addDocument(doc);// 创建一个索引
			}
			iwriter.close();// 创建完索引关闭
			directory.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}
	@Override
	public List<ResumeInfo> queryText(String text) {
		List<ResumeInfo> result = new ArrayList<ResumeInfo>();
		 IndexReader reader = null;
		 try {
			reader = DirectoryReader.open(FSDirectory.open(Paths.get(getClass().getClassLoader().getResource("").toURI())));
			 IndexSearcher searcher = new IndexSearcher(reader); 
//			 Analyzer analyzer = new StandardAnalyzer();
			 Analyzer analyzer = new JcsegAnalyzer(JcsegTaskConfig.COMPLEX_MODE);
			 //  排序  
	            Sort sort = new Sort();  
	            sort.setSort(new SortField("htmlText", Type.SCORE)); // 默认为升序  
//	            Term t1 = new Term("htmlText",text);
	            
	            //lucene 5.x不建议使用filter,而使用BooleanQuery来代替  
	            //Filter filter = new TermFilter(new Term("title", "A"));  
	            // 2、搜索解析器  
	            QueryParser parser = new QueryParser("htmlText", analyzer);  
	            Query query = parser.parse(text);  
//	            Query query = new TermQuery(t1);
	            //lucene 4.x 此方法已经过时，不建议使用filter,而使用BooleanQuery来代替  
//	            TopDocs topDocs = searcher.search(query, filter, Integer.MAX_VALUE, sort);   
	            TopDocs topDocs = searcher.search(query,Integer.MAX_VALUE,sort);  
	            int recordCount = topDocs.totalHits;  
	            int i=0;
	            for(ScoreDoc sd:topDocs.scoreDocs){
	            	int docSn = sd.doc;
	            	Document document = searcher.doc(docSn);
	            	System.out.println(document.get("htmlText"));
	            	ResumeInfo info = new ResumeInfo();
	            	info.setText(document.get("htmlText"));
	            	result.add(info);
	            	i++;
	            	if(i>10)
	            		break;
	            }
	            System.out.println("总共有【" + recordCount + "】条匹配结果");  
		} catch (Exception e) {
			e.printStackTrace();
		}  
		return result;
	}

}
